/*
 * Copyright 2007 Yegor Jbanov
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.spicesoft.clientobjects;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import com.spicesoft.clientobjects.core.BeanMetadata;
import com.spicesoft.clientobjects.core.MethodUtils;

/**
 * <p>This class represents a static registry of POJO classes that
 * are going to be enhanced in the application. This class is not
 * thread-safe.</p>
 * 
 * <p>Why do we need a registry? Why not enhance every object that is
 * passed into the {@link BeanEnhancer}'s constructor?</p>
 * 
 * <p>BeanRegistry tries to solve the problem with POJO beans that
 * contain other POJO beans in their fields. When a registered POJO
 * containing another registered POJO is enhanced the contained
 * POJO is also enhanced automatically.</p>
 * 
 * <p>For details see {@link BeanEnhancer}.</p>
 * 
 * @author Yegor Jbanov
 */
public class BeanRegistry {

  private static final List<Class<?>> pojoTypes = new ArrayList<Class<?>>();
  private static final Map<Class<?>, BeanMetadata> beanMetadataCache = new HashMap<Class<?>, BeanMetadata>();
  
  public static void registerType(Class<?> c) {
    if (!isRegistered(c)) {
      pojoTypes.add(c);
    }
  }
  
  public static boolean isRegistered(Class<?> c) {
    return pojoTypes.contains(c);
  }

  public static BeanMetadata getBeanMetadata(Class<?> clazz) {
    BeanMetadata data = beanMetadataCache.get(clazz);
    
    if (data == null) {
      data = MethodUtils.getBeanMetadata(clazz);
      beanMetadataCache.put(clazz, data);
    }
    
    return data;
  }
  
}
